<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        span.active{
            color: red;
        }
    </style>
</head>
<body>

    <div id="app">
        <div>
            <!-- 让index=0的name变成红色 -->
            <span @click="handlerClick(index, category.id)" v-for="(category, index) in categoryList" :key="category.id" :class = '{active:currentIndex==index}'>
                {{ category.name }}
            </span>
        </div>
    </div>

    <script src="./vue.js"></script>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script>
        let vm = new Vue({
            el:"#app",
            data() {
                return {
                    categoryList: [],
                    currentIndex:0,
                }
            },
            methods: {
                handlerClick(index, id) {
                    this.currentIndex = index;
                    $.ajax({
                        url:`http://localhost:8094/achievement/test2Info?categoryId=${id}`,
                        type: 'get',
                        success: (data) => {
                            console.log(data)
                        },
                        error: (err) => {
                            console.log(err)
                        }
                    });
                }
            },
            // Vue 创建完成执行的钩子函数
            created() {
                $.ajax({
                    url: "http://localhost:8094/achievement/test2",
                    type: "get",
                    success: (data) => {
                        console.log(data);
                        if (data.code === 200) {

                            let obj = {
                                id:0,
                                name: "全部",
                            }

                            // 使用箭头函数, this才是Vue对象, 使用function , this是ajax对象
                            // 能用箭头函数就不用用匿名函数
                            this.categoryList = data.result;
                            // 在数组头填家元素
                            this.categoryList.unshift(obj)
                        }
                    },
                    error: (err) => {
                        console.log(err);
                    }
                });
            },
        });
    </script>
</body>
</html>